package cn.buk.tms.dao;

import cn.buk.tms.entity.misc.AmountHistory;
import cn.buk.tms.entity.misc.EnterpriseBalance;
import cn.buk.tms.entity.misc.ProductBought;
import cn.buk.common.util.DateUtil;
import jakarta.transaction.Transactional;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

/**
 * Created with IntelliJ IDEA.
 * User: yfdai
 * Date: 14-4-22
 * Time: 上午12:08
 * To change this template use File | Settings | File Templates.
 */
@Component
@Transactional
public class TransactionDaoImpl extends AbstractDao implements TransactionDao {

    private final static Logger logger = LogManager.getLogger(TransactionDaoImpl.class);

    /**
     * 购买服务的交易处理(使用积分购买）
     * @param productBought
     * @param fee
     * @param userId
     * @return
     *  100: 成功
     *    1: 余额不足
     *   -1: 出现意外错误
     */
    @Override
    public int buyProductByPoints(ProductBought productBought, final int fee, final int userId) {
        int retCode = 0;

        final int enterpriseId = productBought.getEnterpriseId();

        EnterpriseBalance entBalance = doGetEnterpriseBalance(enterpriseId, em);
        if (entBalance.getBitcoinBalance() < fee) {
            retCode = 1;
            //日志
            throw new RuntimeException("Points is not enough.");
        } else {
            AmountHistory amountHistory = new AmountHistory();
            amountHistory.setOrderType(10); //积分账户
            amountHistory.setUserId(userId);
            amountHistory.setEnterpriseId(enterpriseId);
            amountHistory.setDebt(fee);
            amountHistory.setRemark(productBought.getRemark());

            entBalance.decBitcoinBalance(fee);

            ProductBought productBoughtOld = em.find(ProductBought.class, productBought.getId());
            if (productBoughtOld != null) {

                productBoughtOld.setEndTime(productBought.getEndTime());
                productBoughtOld.setRemark(productBought.getRemark());
                productBoughtOld.setBoughtCount(productBought.getBoughtCount());
                productBoughtOld.setBoughtTime(DateUtil.getCurDateTime());

                em.merge(productBoughtOld);
            } else {
                em.persist(productBought);
            }
            em.merge(entBalance);
            em.persist(amountHistory);


            retCode = 100;
        }

        return retCode;
    }

    @Override
    public int consumePoints(final int enterpriseId, int userId, int amount, String remark) {
        int retCode = 0;

        EnterpriseBalance entBalance = doGetEnterpriseBalance(enterpriseId, em);
        if (entBalance.getBitcoinBalance() < amount) {
            retCode = 1;
            //日志
            throw new RuntimeException("Points is not enough.");
        } else {
            AmountHistory amountHistory = new AmountHistory();
            amountHistory.setOrderType(10); //积分账户
            amountHistory.setUserId(userId);
            amountHistory.setEnterpriseId(enterpriseId);
            amountHistory.setDebt(amount);
            amountHistory.setRemark(remark);

            entBalance.decBitcoinBalance(amount);

            em.merge(entBalance);
            em.persist(amountHistory);


            retCode = 100;
        }

        return retCode;
    }

    /**
     * 购买服务的交易处理(使用现金账户购买）
     * @param productBought
     * @param fee
     * @param userId
     * @return
     *  100: 成功
     *    1: 余额不足
     *   -1: 出现意外错误
     */
    @Override
    public int buyProductByCash(ProductBought productBought, int fee, int userId) {
        int retCode = 0;

        final int enterpriseId = productBought.getEnterpriseId();

        EnterpriseBalance entBalance = doGetEnterpriseBalance(enterpriseId, em);
        if (entBalance.getCashBalance() < fee) {
            retCode = 1;
            //日志
            throw new RuntimeException("现金账户余额不足(Cash balance is not enough).");
        } else {
            AmountHistory amountHistory = new AmountHistory();
            amountHistory.setOrderType(50); //产品购买
            amountHistory.setUserId(userId);
            amountHistory.setEnterpriseId(enterpriseId);
            amountHistory.setDebt(fee);
            amountHistory.setRemark(productBought.getRemark());

            entBalance.decCashBalance(fee);
            amountHistory.setAccountBalance(entBalance.getCashBalance());

            ProductBought productBoughtOld = em.find(ProductBought.class, productBought.getId());
            if (productBoughtOld != null) {
                productBoughtOld.setEndTime(productBought.getEndTime());
                productBoughtOld.setRemark(productBought.getRemark());
                productBoughtOld.setBoughtCount(productBought.getBoughtCount());
                productBoughtOld.setBoughtTime(DateUtil.getCurDateTime());

                em.merge(productBoughtOld);
            } else {
                em.persist(productBought);
            }

            em.merge(entBalance);
            em.persist(amountHistory);


            retCode = 100;
        }

        return retCode;
    }
}
